<template>
  <div class="p-4 bg-white rounded-lg ">
    <div>

      <span :class="`${commonStyle} text-yellow-500`" v-if="status === 1">已扫码，待确认</span>
      <span :class="`${commonStyle} text-green-500`" v-else-if="status === 2">扫码完成</span>
      <span :class="`${commonStyle} text-red-500`" v-else-if="status === 3">用户取消扫码</span>
      <span :class="`${commonStyle} text-black-500`" v-else-if="status === 4">二维码已过期</span>
      <img
          :src="qrCode"
          alt="二维码"
          class="w-48 h-48"
      >
      <span class="text-center block font-bold">{{ time }}s</span>
    </div>
  </div>
  <p class="text-gray-500">请使用花伴APP扫码登录</p>
</template>
<script setup>
import {ref, onMounted,onUnmounted} from 'vue'
import request from "@/utils/request.js";
import {useUserStore} from "@/stores/user.js";
import router from "@/router/index.js";

// 通用样式
const commonStyle = 'absolute w-48 h-48 flex justify-center items-center bg-opacity-80 bg-gray-500 font-bold text-xl'
const time = ref(15)
const qrCode = ref('')
const status = ref(0)
let timer1;
let timer2;
let uuid;
const userStore = useUserStore();
// 获取二维码
const getQrCode = async () => {
  const load = async () => {
    if (time.value <= 1) {
      // 随机字符串
      time.value = 15
      getSrc()
      return
    }
    const {data} = await request.get("/user/getQrStatus?uuid=" + uuid)
    status.value = data.status
    time.value--
    // 登录成功
    if (status.value === 2) {
      userStore.setUserInfo(data)
      await router.push("/")
    } else {
      timer1 = setTimeout(load, 1000)
    }
  }
  await load()
}
// 给二维码赋值
const getSrc = () => {
  status.value = 0
  uuid = Math.random().toString(36).substring(2, 15);
  qrCode.value = "/api/user/getQr?uuid=" + uuid
  // 延迟下，等图片先加载
  timer2 = setTimeout(getQrCode,100)
}

onMounted(() => {
  getSrc()
})
onUnmounted(() => {
  clearTimeout(timer1)
  clearTimeout(timer2)
})
</script>

<style scoped>

</style>
